import 'dart:io';
import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io' show File, Directory;
import '../../function/widgets/toast_widget.dart';
import '../../function/states/user_state.dart';

/// 用户信息编辑页面
class UserProfileEditor extends StatefulWidget {
  const UserProfileEditor({super.key});

  @override
  State<UserProfileEditor> createState() => _UserProfileEditorState();
}

class _UserProfileEditorState extends State<UserProfileEditor> {
  final TextEditingController _nameController = TextEditingController();
  String _tempUserName = '';
  String _tempAvatarPath = '';

  @override
  void initState() {
    super.initState();
    _initializeUserData();
  }

  @override
  void dispose() {
    _nameController.dispose();
    super.dispose();
  }

  /// 初始化用户数据
  void _initializeUserData() {
    final currentUser = UserState.getCurrentUserInfo();
    if (currentUser != null) {
      _tempUserName = currentUser.userName;
      _tempAvatarPath = currentUser.avatar;
      _nameController.text = currentUser.userName;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/common_bg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 顶部导航栏
              _buildTopNavigationBar(),

              // 编辑内容
              Expanded(child: _buildEditContent()),

              // 确认按钮
              _buildConfirmButton(),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildTopNavigationBar() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 0.h),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => Get.back(),
            child: Icon(Icons.arrow_back_ios, color: Colors.white, size: 22.sp),
          ),
          SizedBox(width: 16.w),
          Text('Personal Information')
              .fontSize(18.sp)
              .textColor(Colors.white)
              .fontFamily(
                GoogleFonts.quicksand(fontWeight: FontWeight.w700).fontFamily,
              )
              .fontWeight(FontWeight.w700),
        ],
      ),
    );
  }

  /// 构建编辑内容
  Widget _buildEditContent() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: Column(
        children: [
          SizedBox(height: 40.h),

          // 头像编辑区域
          _buildAvatarSection(),

          SizedBox(height: 40.h),

          // 用户名编辑区域
          _buildUserNameSection(),
        ],
      ),
    );
  }

  /// 构建头像编辑区域
  Widget _buildAvatarSection() {
    return Column(
      children: [
        // 头像
        GestureDetector(
          onTap: _selectAvatarImage,
          child: Stack(
            children: [
              Container(
                width: 120.w,
                height: 120.w,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  border: Border.all(
                    color: Colors.white.withOpacity(0.3),
                    width: 3.w,
                  ),
                ),
                child: ClipOval(
                  child:
                      _tempAvatarPath.isNotEmpty
                          ? (_tempAvatarPath.startsWith('assets/')
                              ? Image.asset(
                                _tempAvatarPath,
                                width: 120.w,
                                height: 120.w,
                                fit: BoxFit.cover,
                              )
                              : Image.file(
                                File(_tempAvatarPath),
                                width: 120.w,
                                height: 120.w,
                                fit: BoxFit.cover,
                              ))
                          : Container(
                            color: Colors.grey.withOpacity(0.3),
                            child: Icon(
                              Icons.person,
                              color: Colors.white.withOpacity(0.6),
                              size: 60.w,
                            ),
                          ),
                ),
              ),

              // 编辑图标
              Positioned(
                bottom: 0,
                right: 0,
                child: Container(
                  width: 36.w,
                  height: 36.w,
                  decoration: BoxDecoration(
                    color: const Color(0xFFFF8A3C),
                    shape: BoxShape.circle,
                    border: Border.all(color: Colors.white, width: 2.w),
                  ),
                  child: Icon(
                    Icons.camera_alt,
                    color: Colors.white,
                    size: 18.w,
                  ),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// 构建用户名编辑区域
  Widget _buildUserNameSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Name')
            .fontSize(16.sp)
            .textColor(Colors.white)
            .fontWeight(FontWeight.w600)
            .fontFamily(
              GoogleFonts.quicksand(fontWeight: FontWeight.w600).fontFamily,
            ),

        SizedBox(height: 12.h),

        GestureDetector(
          onTap: _showEditNameDialog,
          child: Container(
            width: double.infinity,
            padding: EdgeInsets.symmetric(vertical: 16.h, horizontal: 20.w),
            decoration: BoxDecoration(
              color: const Color(0xFF8B4513).withOpacity(0.8),
              borderRadius: BorderRadius.circular(12.r),
              border: Border.all(
                color: const Color(0xFFFF8A3C).withOpacity(0.3),
                width: 1.w,
              ),
            ),
            child: Row(
              children: [
                Expanded(
                  child: Text(
                        _tempUserName.isEmpty
                            ? 'Modify and re-enter your name'
                            : _tempUserName,
                      )
                      .fontSize(16.sp)
                      .textColor(
                        _tempUserName.isEmpty
                            ? Colors.white.withOpacity(0.6)
                            : Colors.white,
                      )
                      .fontWeight(FontWeight.w500)
                      .fontFamily(
                        GoogleFonts.quicksand(
                          fontWeight: FontWeight.w500,
                        ).fontFamily,
                      ),
                ),
                Icon(
                  Icons.edit,
                  color: Colors.white.withOpacity(0.6),
                  size: 20.w,
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// 构建确认按钮
  Widget _buildConfirmButton() {
    return Padding(
      padding: EdgeInsets.all(20.w),
      child: GestureDetector(
        onTap: _saveUserInfo,
        child: Container(
          width: double.infinity,
          padding: EdgeInsets.symmetric(vertical: 16.h),
          decoration: BoxDecoration(
            color: const Color(0xFF8B4513).withOpacity(0.8),
            borderRadius: BorderRadius.circular(12.r),
            border: Border.all(
              color: const Color(0xFFFF8A3C).withOpacity(0.3),
              width: 1.w,
            ),
          ),
          child: Text('Confirm')
              .fontSize(16.sp)
              .textColor(Colors.white)
              .fontWeight(FontWeight.w700)
              .fontFamily(
                GoogleFonts.quicksand(fontWeight: FontWeight.w700).fontFamily,
              )
              .textAlignment(TextAlign.center),
        ),
      ),
    );
  }

  /// 选择头像图片
  Future<void> _selectAvatarImage() async {
    try {
      final List<AssetEntity>? assets = await AssetPicker.pickAssets(
        context,
        pickerConfig: const AssetPickerConfig(
          maxAssets: 1,
          requestType: RequestType.image,
          specialPickerType: SpecialPickerType.noPreview,
        ),
      );

      if (assets != null && assets.isNotEmpty) {
        final AssetEntity asset = assets.first;
        final File? file = await asset.file;

        if (file != null) {
          // 复制文件到本地目录
          final String localPath = await _copyImageToLocal(file);
          setState(() {
            _tempAvatarPath = localPath;
          });
        }
      }
    } catch (e) {
      ToastWidget.showError('Failed to select image');
    }
  }

  /// 复制图片到本地目录
  Future<String> _copyImageToLocal(File sourceFile) async {
    try {
      final Directory appDir = await getApplicationDocumentsDirectory();
      final String avatarDir = '${appDir.path}/avatars';

      // 创建头像目录
      final Directory avatarDirectory = Directory(avatarDir);
      if (!await avatarDirectory.exists()) {
        await avatarDirectory.create(recursive: true);
      }

      // 生成唯一文件名
      final String fileName =
          'avatar_${DateTime.now().millisecondsSinceEpoch}.jpg';
      final String targetPath = '$avatarDir/$fileName';

      // 复制文件
      await sourceFile.copy(targetPath);

      return targetPath;
    } catch (e) {
      throw Exception('Failed to save image: $e');
    }
  }

  /// 显示编辑用户名对话框
  void _showEditNameDialog() {
    final TextEditingController dialogController = TextEditingController(
      text: _tempUserName,
    );

    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          backgroundColor: const Color(0xFF663507),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16.r),
            side: BorderSide(color: const Color(0xFFFF8A3C), width: 1.w),
          ),
          title: Text('Edit Name')
              .fontSize(18.sp)
              .textColor(Colors.white)
              .fontWeight(FontWeight.w700)
              .textAlignment(TextAlign.center),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text('Enter your new name')
                  .fontSize(14.sp)
                  .textColor(Colors.white.withOpacity(0.8))
                  .textAlignment(TextAlign.center),

              SizedBox(height: 16.h),

              TextField(
                controller: dialogController,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 16.sp,
                  fontFamily:
                      GoogleFonts.quicksand(
                        fontWeight: FontWeight.w500,
                      ).fontFamily,
                ),
                decoration: InputDecoration(
                  hintText: 'Enter your name',
                  hintStyle: TextStyle(
                    color: Colors.white.withOpacity(0.6),
                    fontSize: 16.sp,
                  ),
                  filled: true,
                  fillColor: Colors.white.withOpacity(0.1),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8.r),
                    borderSide: BorderSide(
                      color: const Color(0xFFFF8A3C).withOpacity(0.3),
                    ),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8.r),
                    borderSide: BorderSide(
                      color: const Color(0xFFFF8A3C).withOpacity(0.3),
                    ),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8.r),
                    borderSide: BorderSide(color: const Color(0xFFFF8A3C)),
                  ),
                ),
              ),
            ],
          ),
          actions: [
            Row(
              children: [
                Expanded(
                  child: GestureDetector(
                    onTap: () => Navigator.of(context).pop(),
                    child: Container(
                      padding: EdgeInsets.symmetric(vertical: 12.h),
                      decoration: BoxDecoration(
                        color: Colors.white.withOpacity(0.2),
                        borderRadius: BorderRadius.circular(8.r),
                      ),
                      child: Text('Cancel')
                          .fontSize(14.sp)
                          .textColor(Colors.white)
                          .fontWeight(FontWeight.w600)
                          .textAlignment(TextAlign.center),
                    ),
                  ),
                ),

                SizedBox(width: 12.w),

                Expanded(
                  child: GestureDetector(
                    onTap: () {
                      final String newName = dialogController.text.trim();
                      if (newName.isNotEmpty) {
                        setState(() {
                          _tempUserName = newName;
                        });
                        Navigator.of(context).pop();
                      } else {
                        ToastWidget.showWarning('Name cannot be empty');
                      }
                    },
                    child: Container(
                      padding: EdgeInsets.symmetric(vertical: 12.h),
                      decoration: BoxDecoration(
                        color: const Color(0xFFFF8A3C),
                        borderRadius: BorderRadius.circular(8.r),
                      ),
                      child: Text('Confirm')
                          .fontSize(14.sp)
                          .textColor(Colors.white)
                          .fontWeight(FontWeight.w600)
                          .textAlignment(TextAlign.center),
                    ),
                  ),
                ),
              ],
            ),
          ],
        );
      },
    );
  }

  /// 保存用户信息
  void _saveUserInfo() {
    if (_tempUserName.isEmpty) {
      ToastWidget.showWarning('Please enter your name');
      return;
    }

    try {
      // 更新用户信息
      final bool success = UserState.updateUserProfile(
        userName: _tempUserName,
        avatar: _tempAvatarPath,
      );

      if (success) {
        ToastWidget.showSuccess('Profile updated successfully');
        Get.back();
      } else {
        ToastWidget.showError('Failed to update profile');
      }
    } catch (e) {
      ToastWidget.showError('Failed to update profile');
    }
  }
}
